package cn.xioabai.common.utility;

import cn.hutool.core.util.HexUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 本地执行工具类
 *
 * @Author yangdaji
 * @Date 2022/10/31 0031
 * @PackageName cn.xioabai.utils
 * @ClassName ExecuteUtil
 */
public class ExecuteUtil {

    private static Logger log = LoggerFactory.getLogger(ExecuteUtil.class);

    private final static String CHARSET_NAME = "GBK";

    /**
     * 返回命令返回的结果集, 字符串形式
     *
     * @param cmd cmd 命令
     * @return
     */
    public static String executeToString(String cmd) {
        return bufferedReaderToString(getBufferedReaderFromCmd(cmd));
    }

    /**
     * 获取命令返回的结果集,字符串列表形式
     *
     * @param cmd 命令
     * @return
     */
    public static List<String> executeToStringList(String cmd) {
        return bufferedReaderToStringList(getBufferedReaderFromCmd(cmd));
    }


    /**
     * 读取数据到集合中
     *
     * @param inputStreamReader
     * @return
     */
    public static List<String> bufferedReaderToStringList(InputStreamReader inputStreamReader) {
        List<String> result = new ArrayList<>();
        String line = "";
        try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
            while ((line = bufferedReader.readLine()) != null) {
                result.add(line + "\r\n");
            }
        } catch (IOException ioe) {
            log.error("Invalid command {}", ioe.getMessage());
            return null;
        }
        return result;
    }

    /**
     * 读取数据到为单行
     *
     * @param inputStreamReader
     * @return
     */
    public static String bufferedReaderToString(InputStreamReader inputStreamReader) {
        String line = "";
        StringBuilder sb = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line + "\r\n");
            }
        } catch (IOException ioe) {
            log.error("Invalid command {}", ioe.getMessage());
            return null;
        }
        return sb.toString();
    }


    /**
     * 从 cmd 命令获取读取输入流
     *
     * @param cmd cmd 命令
     * @return
     */
    public static InputStreamReader getBufferedReaderFromCmd(String cmd) {
        try {
            return new InputStreamReader(
                    Runtime.getRuntime().exec(cmd).getInputStream(), CHARSET_NAME);
        } catch (IOException e) {
            log.error("获取 [InputStreamReader] 对象失败: {}", e.getMessage());
            return null;
        }
    }

    /**
     * 字符串转换成为16进制(无需Unicode编码)
     * @param str
     * @return
     */
    public static String str2HexStr(String str) {
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
        }
        return sb.toString().trim();
    }

    /**
     * 字符串转换成为16进制(无需Unicode编码)
     * @param str
     * @return
     */
    public static String str2Hex(String str) {
        return HexUtil.encodeHexStr(str.getBytes());
    }

}
